package com.wudi.aidoctor.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.wudi.aidoctor.agent.Manus;
import com.wudi.aidoctor.app.DoctorApp;
import com.wudi.aidoctor.common.BaseResponse;
import com.wudi.aidoctor.common.ResultUtils;
import com.wudi.aidoctor.constant.UserConstant;
import com.wudi.aidoctor.service.ChatService;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/ai")
public class AiController {

    @Resource
    private DoctorApp doctorApp;

    @Resource
    private ChatModel dashscopeChatModel;

    @Resource
    private ToolCallback[] allTools;

    @Resource
    private ChatService chatService;

    @GetMapping("/doctor_app/chat/sync")
    public BaseResponse<String> doChatWithDoctorAppSync(String message, String chatId) {
        return ResultUtils.success(doctorApp.doChat(message, chatId));
    }

    @GetMapping(value = "/doctor_app/chat/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> doChatWithDoctorAppSSE(String message, String chatId) {
        return doctorApp.doChatByStream(message, chatId);
    }

    @GetMapping("/doctor_app/get/messages")
    public BaseResponse<String> getMessages(String chatId) {
        return ResultUtils.success("");
    }

    /**
     * 流式调用 Manus 超级智能体
     *
     * @param message
     * @return
     */
    @GetMapping("/manus/chat")
    public SseEmitter doChatWithManus(String message) {
        Manus Manus = new Manus(allTools, dashscopeChatModel);
        return Manus.runStream(message);
    }

    @GetMapping("/doctor_app/chat/memory")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<String> doChatWithMemory(String chatId) {
        List<Message> messages = chatService.getMessages(chatId);
        return ResultUtils.success(messages.stream().map(Message::getText).collect(Collectors.joining("\n")));
    }

}
